import type { RequestClient } from './request-client'
import type { MakeErrorMessageFn, ResponseInterceptorConfig } from './types'
import { Message } from '@arco-design/web-vue'

import axios from 'axios'
import { isFunction } from 'lodash-es'
import { getHttpErrorMessage } from './utils'

export function defaultResponseInterceptor({
  codeField = 'code',
  dataField = 'data',
  successCode = 0,
}: {
  /** 响应数据中代表访问结果的字段名 */
  codeField: string
  /** 响应数据中装载实际数据的字段名，或者提供一个函数从响应数据中解析需要返回的数据 */
  dataField: ((response: any) => any) | string
  /** 当codeField所指定的字段值与successCode相同时，代表接口访问成功。如果提供一个函数，则返回true代表接口访问成功 */
  successCode: ((code: any) => boolean) | number | string
}): ResponseInterceptorConfig {
  return {
    fulfilled: (response) => {
      const { config, data: responseData, status } = response

      if (status >= 200 && status < 400) {
        if (config.responseReturn === 'raw') {
          return response
        }
        if (config.responseReturn === 'body') {
          return responseData
        }
        if (
          isFunction(successCode)
            ? successCode(responseData[codeField])
            : responseData[codeField] === successCode
        ) {
          return isFunction(dataField)
            ? dataField(responseData)
            : responseData[dataField]
        }
      }
      throw Object.assign({}, response, { response })
    },
  }
}

export function authenticateResponseInterceptor({
  client,
  doReAuthenticate,
  doRefreshToken,
  enableRefreshToken,
  formatToken,
}: {
  client: RequestClient
  doReAuthenticate?: () => Promise<void>
  doRefreshToken?: () => Promise<string>
  enableRefreshToken: boolean
  formatToken: (token: string) => null | string
}): ResponseInterceptorConfig {
  return {
    fulfilled: async (response) => {
      const {
        data: { code, message },
      } = response
      if (String(code).endsWith('6401')) {
        CookieHelper.remove()
        Message.clear()
        Message.error(message)
        const { href, origin } = window.location
        const fullPath = href?.replace(origin, '')
        window.location.replace(`${origin}/sign-in?redirect=${fullPath}`)
        return Promise.reject(
          new Error(response?.message || 'Authentication failed'),
        )
      }
      return response
    },
    rejected: async (error) => {
      const { config, response } = error
      // 如果不是 401 停止处理
      if (response?.status !== 401) {
        return response
      }
      // 判断是否启用了 refreshToken 功能
      // 如果没有启用或者已经是重试请求了，直接跳转到重新登录
      if (!enableRefreshToken || config.__isRetryRequest) {
        if (!doReAuthenticate || typeof doReAuthenticate !== 'function') {
          throw new Error('doReAuthenticate 必填并为函数')
        }
        await doReAuthenticate()
        throw error
      }
      // 如果正在刷新 token，则将请求加入队列，等待刷新完成
      if (client.isRefreshing) {
        return new Promise((resolve) => {
          client.refreshTokenQueue.push((newToken: string) => {
            config.headers.Authorization = formatToken(newToken)
            resolve(client.request(config.url, { ...config }))
          })
        })
      }

      // 标记开始刷新 token
      client.isRefreshing = true
      // 标记当前请求为重试请求，避免无限循环
      config.__isRetryRequest = true

      if (!doRefreshToken || typeof doRefreshToken !== 'function') {
        throw new Error('doRefreshToken 必填并为函数')
      }
      try {
        const newToken = await doRefreshToken()

        // 处理队列中的请求
        client.refreshTokenQueue.forEach(callback => callback(newToken))
        // 清空队列
        client.refreshTokenQueue = []

        return client.request(error.config.url, { ...error.config })
      } catch (refreshError) {
        // 如果刷新 token 失败，处理错误（如强制登出或跳转登录页面）
        client.refreshTokenQueue.forEach(callback => callback(''))
        client.refreshTokenQueue = []
        console.error('刷新 token 失败，请重新登录')

        if (!doReAuthenticate || typeof doReAuthenticate !== 'function') {
          throw new Error('doReAuthenticate 必填并为函数')
        }
        await doReAuthenticate()

        throw refreshError
      } finally {
        client.isRefreshing = false
      }
    },
  }
}

export function errorMessageResponseInterceptor(
  makeErrorMessage?: MakeErrorMessageFn,
): ResponseInterceptorConfig {
  return {
    rejected: (error: any) => {
      if (axios.isCancel(error)) {
        return Promise.reject(error)
      }

      const err: string = error?.toString?.() ?? ''
      let errMsg = ''

      if (err?.includes('Network Error')) {
        // http.networkError 网络异常，请检查您的网络连接后重试
        errMsg = getHttpErrorMessage('networkError')!
      } else if (error?.message?.includes?.('timeout')) {
        // http.requestTimeout 请求超时，请稍后重试
        errMsg = getHttpErrorMessage('408')!
      }
      if (errMsg) {
        makeErrorMessage?.(errMsg, error)
        return Promise.reject(error)
      }
      const status
        = error?.response?.data?.code || error?.response?.status || 500
      makeErrorMessage?.(
        getHttpErrorMessage(status) || error?.response?.data?.message || '',
        error,
      )

      return Promise.reject(error)
    },
  }
}
